package com.example.myapplication

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController

/**
 * A simple [Fragment] subclass as the default destination in the navigation.
 */
class FirstFragment : Fragment() {

    override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 监听random_button(点击跳转页面)
        view.findViewById<Button>(R.id.random_button).setOnClickListener {
            // 获得传递的值
            val showCountTextView = view.findViewById<TextView>(R.id.textview_first)
            val max_random = showCountTextView.text.toString().toInt()

            val bundle = Bundle()
            bundle.putInt("max_random", max_random)

            // 点击按钮进行跳转
            val action = FirstFragmentDirections.actionFirstFragmentToSecondFragment(max_random)
            findNavController().navigate(action)
        }

        // 监听toast_button(显示提示信息)
        view.findViewById<Button>(R.id.toast_button).setOnClickListener {
            // 创建弹窗(上下文环境,显示信息,显示时间)
            val myToast = Toast.makeText(context, "Hello Toast!", Toast.LENGTH_LONG)
            // 显示弹窗
            myToast.show()
        }

        // 监听count_button(计数)
        view.findViewById<Button>(R.id.count_button).setOnClickListener {
            countMe(view)
        }
    }

    private fun countMe(view: View) {
        // Get the text view
        val showCountTextView = view.findViewById<TextView>(R.id.textview_first)

        // Get the value of the text view.
        val countString = showCountTextView.text.toString()

        // Convert value to a number and increment it
        var count = countString.toInt()
        count++

        // Display the new value in the text view.
        showCountTextView.text = count.toString()
    }
}